package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserIdHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * 检查用户是否已经完成登录
 */
@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 判断 uri地址 是否登录相关
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();
        // 是登录相关 不需要处理 直接放行
        if (isMatch(requestURI)) {
            chain.doFilter(request, response);
            return;
        }
        // 不是登录相关的 判断是否登录, 即 session中是否有 雇员/用户 的id
        //4-1、判断员工登录状态，如果已登录，则直接放行
        String _employeeId = (String) req.getSession().getAttribute("employeeId");
        if (StringUtils.isNotBlank(_employeeId)) {
            //从 Session 中 获取 empId , 并存入 ThreadLocal 对象中
            log.info("已登录的 employeeId " + _employeeId);
            Long employeeId = Long.valueOf(_employeeId);
            UserIdHolder.set(employeeId);
            // session中有用户的id 放行
            chain.doFilter(request, response);
            UserIdHolder.remove();
            return;
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        String _userId = (String) req.getSession().getAttribute("userId");
        if (StringUtils.isNotBlank(_userId)) {
            log.info("用户已登录，用户id为: " + _userId);
            Long userId = Long.valueOf(_userId);
            UserIdHolder.set(userId);
            chain.doFilter(request, response);
            UserIdHolder.remove();
            return;
        }

        // session中没有 雇员或用户的id 则是非法访问，返回错误信息： {"data": null ,"code": 0 ,"msg": "NOTLOGIN"}
        R<String> r = R.error("NOTLOGIN");
        String s = JSON.toJSONString(r);
        response.getWriter().write(s);
    }

    boolean isMatch(String str) {
        String[] strings = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        for (String string : strings) {
            if (PATH_MATCHER.match(string, str)) {
                return true;
            }
        }
        return false;
    }
}
